package vip.xiaonuo.core.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

public class RarUtil {
    protected static Log log = LogFactory.getLog("RarUtil");

    /**
     * 采用命令行方式解压文件
     *
     * @param multipartFile 压缩文件
     * @return
     */
    public static boolean extractRar(MultipartFile multipartFile, String extractFileFolder) throws Exception {
        String fileName = multipartFile.getOriginalFilename();
        File saveFile = File.createTempFile(StringUtils.substringBefore(fileName, "."),
                "." + StringUtils.substringAfter(fileName, "."));
        multipartFile.transferTo(saveFile);
        // 获取windows中 WinRAR.exe的路径
        boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");
        final boolean isLinux = System.getProperty("os.name").toLowerCase().contains("linux");

        // 开始调用命令行解压，参数-o+是表示覆盖的意思
        String cmd = "";
        if (isWin) {
            // This path is my computer's configuration，if you deploy it to a windows server,please change it.
            String winRarPath = "\"C:\\Program Files\\WinRAR\\WinRAR.exe\"";
            cmd = winRarPath + " X -o+ " + saveFile.getAbsolutePath() + " " + extractFileFolder;
        } else if (isLinux) {
            cmd = "rar" + " X -o+ " + saveFile.getAbsolutePath() + " " + extractFileFolder;
        }
        log.debug("cmd=" + cmd);
        Process proc = Runtime.getRuntime().exec(cmd);
        return proc.waitFor() == 0 || proc.exitValue() != 0;
    }
}
